package com.dal.rpc.core.common;

import com.dal.rpc.core.enums.PackageType;
import com.dal.rpc.core.serializer.Serializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * @program: dal-springboot
 * @description: netty 编码器
 * @author: jian
 * @create: 2021-11-17 11:33
 */
public class NettyEncoder extends MessageToByteEncoder {

    private static final int MAGIC_NUMBER = 0xCAFEBABE;

    private Class<?> genericClass;
    private Serializer serialize;

    /**
     * 构造函数传入向反序列化的class
     *
     * @param serialize
     */
    public NettyEncoder(Serializer serialize) {
        this.serialize = serialize;
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, Object o, ByteBuf out) throws Exception {
        //if (genericClass.isInstance(o)) {
            //发送魔数
            out.writeInt(MAGIC_NUMBER);
            //发送PackgeType
            if (o instanceof RpcRequest) {
                out.writeInt(PackageType.REQUEST_PACK.getCode());
            } else {
                out.writeInt(PackageType.RESPONSE_PACK.getCode());
            }
            //发送序列化类型
            out.writeInt(serialize.getCode());
            byte[] bytes = serialize.serialize(o);
            //发送信息长度
            out.writeInt(bytes.length);
            //发送信息
            out.writeBytes(bytes);
        //}
    }
}
